<template>
	<div class="paper">
		<div class="serach">
			<el-input
				v-model="examinationName"
				placeholder="请输入试卷名称"
				style="width: 400px"
			></el-input>
			<el-button style="margin-left: 20px" type="primary" @click="getExamList">查询试卷</el-button>
			<el-button type="success" @click="add">新增试卷</el-button>
			<el-button type="info" @click="download">下载模板</el-button>
		</div>
		<div class="list">
			<el-table
				:data="tableData"
				style="width: 100%"
				:header-cell-style="{ 'text-align': 'center' }"
				:cell-style="{ 'text-align': 'center' }"
			>
				<!-- <el-table-column type="index" label="序号"> </el-table-column> -->
				<el-table-column label="试卷类型">
					<template slot-scope="scope">{{
						scope.row.ishost == 1 ? '试卷1' : scope.row.ishost == 2 ? '试卷2' : ''
					}}</template>
				</el-table-column>
				<el-table-column prop="examinationName" label="试卷名称"> </el-table-column>
				<el-table-column label="分值">
					<template slot-scope="scope">100</template>
				</el-table-column>
				<el-table-column label="试卷题型">
					<template slot-scope="scope">单选</template></el-table-column
				>
				<el-table-column label="操作">
					<template slot-scope="scope">
						<el-button type="text" @click="edit(scope.row)">编辑</el-button>
						<el-button type="text" @click="del(scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<div class="page">
			<el-pagination
				align="center"
				background
				layout="total,prev, pager, next"
				:page-size="5"
				:total="total"
				@current-change="currentChange"
			>
			</el-pagination>
		</div>
		<el-dialog
			v-if="dialogVisible"
			:close-on-click-modal="false"
			:title="dialogTitle"
			:visible.sync="dialogVisible"
			:before-close="handleClose"
			width="70%"
		>
			<el-form ref="form" :model="form" label-width="120px">
				<el-form-item label="试卷名称：">
					<el-input
						v-model="form.examinationName"
						placeholder="请输入试卷名称(上传文件可被覆盖)"
					></el-input>
				</el-form-item>
				<el-form-item label="试卷类型：" placeholder="请选择试卷类型">
					<el-select v-model="form.ishost" style="width: 100%">
						<el-option label="试卷1" value="1"> </el-option>
						<el-option label="试卷2" value="2"> </el-option
					></el-select>
				</el-form-item>
				<el-form-item label="听力音频：">
					<el-upload action="#" :file-list="audioFileList" :http-request="upAudio">
						<el-button size="small" type="primary">点击上传</el-button>
					</el-upload>
				</el-form-item>
				<el-form-item label="听力原文：">
					<el-upload action="#" :file-list="pdfFileList" :http-request="upPdf">
						<el-button size="small" type="primary">点击上传</el-button>
					</el-upload>
				</el-form-item>
				<el-form-item label="分值：">
					<el-input value="100"></el-input>
				</el-form-item>
				<el-form-item label="试卷时间：">
					<el-date-picker
						style="width: 100%"
						v-model="form.time"
						type="month"
						placeholder="选择时间"
						value-format="yyyy/MM"
					>
					</el-date-picker>
				</el-form-item>
				<el-form-item label="添加试卷方式：">
					<el-select v-model="isUpload" style="width: 100%">
						<el-option label="上传" :value="true"> </el-option>
						<el-option label="录入" :value="false"> </el-option
					></el-select>
				</el-form-item>
				<el-form-item label="试卷：">
					<el-table
						v-if="!isUpload"
						:data="form.test"
						style="width: 100%"
						:header-cell-style="{ 'text-align': 'center' }"
						:cell-style="{ 'text-align': 'center' }"
					>
						<el-table-column prop="order" label="排序" width="60"> </el-table-column>
						<el-table-column label="选择题">
							<el-table-column label="A">
								<template slot-scope="scope">
									<el-input v-model="scope.row.option[0]"></el-input>
								</template>
							</el-table-column>
							<el-table-column label="B">
								<template slot-scope="scope">
									<el-input v-model="scope.row.option[1]"></el-input>
								</template>
							</el-table-column>
							<el-table-column label="C">
								<template slot-scope="scope">
									<el-input v-model="scope.row.option[2]"></el-input> </template
							></el-table-column>
							<el-table-column label="D">
								<template slot-scope="scope">
									<el-input v-model="scope.row.option[3]"></el-input>
								</template>
							</el-table-column>
						</el-table-column>
						<el-table-column prop="answer" label="正确答案">
							<template slot-scope="scope">
								<el-input v-model="scope.row.answer"></el-input>
							</template>
						</el-table-column>
					</el-table>
					<el-upload v-else action="#" :http-request="upExcelCleateExamation">
						<el-button size="small" type="primary">点击上传</el-button>
					</el-upload>
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer">
				<el-button @click="handleClose">取 消</el-button>
				<el-button type="primary" @click="submit" :loading="isExamTime">确 定</el-button>
			</span>
		</el-dialog>
	</div>
</template>

<script>
	import { getExam, editExam, setPaper, deleteExam, upExcelCleateExamation } from '@/api/admin';
	import { upFile } from '@/api/login';
	import { getTestInfo } from '@/api/user';
	export default {
		data() {
			return {
				tableData: [],
				examinationName: '',
				currPage: 1,
				total: 0,
				form: {
					test: [],
				},
				dialogTitle: '新增试卷',
				dialogVisible: false,
				audioFileList: [],
				pdfFileList: [],
				isExamTime: false,
				isUpload: true,
			};
		},
		created() {
			this.getExamList();
		},
		methods: {
			async getExamList() {
				let params = {
					currPage: this.currPage,
					pageSize: 5,
					examinationName: this.examinationName,
				};
				let data = await getExam(params);
				this.tableData = data.data.data.list;
				this.total = data.data.data.total;
			},
			add() {
				this.isUpload = true;
				this.dialogTitle = '新增试卷';
				this.dialogVisible = true;
				let test = [];
				for (let i = 1; i <= 25; i++) {
					test.push({
						answer: '',
						option: new Array(4).fill(''),
						order: i,
					});
				}
				this.form = { test };
			},
			async edit(row) {
				this.isUpload = false;
				this.dialogTitle = '编辑试卷';
				delete row.audioId;
				this.form = { ...row, examinationId: row.id };
				let params = {
					examinationId: row.id,
				};
				let res = await getTestInfo(params);
				this.form.test = res.data.data.test.map((item) => {
					item.option = item.optionList.split(',').map((item) => item.split(')')[1]);
					item.order = item.orderNum;
					delete item.orderNum;
					delete item.optionList;
					delete item.id;
					return item;
				});
				this.audioFileList = [{ name: row.audioUrl, url: row.audioUrl }];
				this.pdfFileList = [{ name: row.originalUrl, url: row.originalUrl }];
				this.dialogVisible = true;
			},
			del(row) {
				this.$modal.confirm('确认要删除吗?').then(async () => {
					let params = { id: row.id };
					let res = await deleteExam(params);
					this.$modal.msgSuccess(res.data.msg);
					this.getExamList();
				});
			},
			async submit() {
				let optionMap = {
					0: 'A',
					1: 'B',
					2: 'C',
					3: 'D',
				};
				let examData = JSON.parse(JSON.stringify(this.form));
				examData.test.forEach((item) => {
					item.option = item.option.map((v, index) => {
						let r = (v && v.replace(/'/g, '"')) || '';
						return optionMap[index] + ')' + r;
					});
				});
				if (this.dialogTitle == '编辑试卷') {
					let params = {
						id: this.form.id,
						examData: JSON.stringify(examData),
					};
					let res = await editExam(params);
					this.$modal.msgSuccess(res.data.msg);
				}
				if (this.dialogTitle == '新增试卷') {
					let params = {
						examData: JSON.stringify(examData),
					};
					let res = await setPaper(params);
					this.$modal.msgSuccess(res.data.msg);
				}
				this.dialogVisible = false;
				this.getExamList();
			},
			async getExamTime(src) {
				const audio = new Audio();
				audio.src = this.$baseUrl + src;
				const countAudioTime = async () => {
					while (isNaN(audio.duration) || audio.duration === Infinity) {
						// 延迟一会 不然网页都卡死
						await new Promise((resolve) => setTimeout(resolve, 200));
						// 设置随机播放时间，模拟调进度条
						audio.currentTime = 10000000 * Math.random();
					}
					return audio.duration;
				};
				let audioTime = await countAudioTime();
				let examTime = Math.ceil(audioTime / 60) + 1;
				return examTime;
			},
			currentChange(v) {
				this.currPage = v;
				this.getExamList();
			},
			async upFile({ file }) {
				let params = new FormData();
				params.append('upFile', file);
				let res = await upFile(params);
				this.$set(this.form, 'avatarUrl', this.$baseUrl + res.data.data.audioPath);
			},
			async upAudio({ file }) {
				let params = new FormData();
				params.append('upFile', file);
				this.audioFileList = [];
				this.isExamTime = true;
				this.$modal.msg('请等待文件上传结束...');
				let res = await upFile(params);
				this.form.audioUrl = res.data.data.audioPath;
				this.isExamTime = false;
				this.$set(this.audioFileList, 0, {
					name: res.data.data.audioPath,
					url: res.data.data.audioPath,
				});
				if (file.size == 0) {
					this.form.examTime = examTime;
				} else {
					this.isExamTime = true;
					this.$modal.msg('请等待获取时长...');
					this.getExamTime(res.data.data.audioPath).then((res) => {
						this.form.examTime = res;
						this.isExamTime = false;
					});
				}
			},
			async upPdf({ file }) {
				this.isExamTime = true;
				this.$modal.msg('请等待文件上传结束...');
				let params = new FormData();
				params.append('upFile', file);
				this.isExamTime = false;
				this.pdfFileList = [];
				let res = await upFile(params);
				this.$set(this.pdfFileList, 0, {
					name: res.data.data.audioPath,
					url: res.data.data.audioPath,
				});
				this.form.originalUrl = res.data.data.audioPath;
			},
			async upExcelCleateExamation({ file }) {
				this.isExamTime = true;
				this.$modal.msg('请等待文件上传结束...');
				let params = new FormData();
				params.append('upFile', file);
				let res = await upExcelCleateExamation(params);
				this.isExamTime = false;
				let { test, examinationName } = res.data.data;
				this.$set(this.form, 'test', test);
				this.$set(this.form, 'examinationName', examinationName);
				this.isUpload = false;
			},
			download() {
				window.open(this.$baseUrl + '/static/mould/试卷模板.xlsx');
			},
			handleClose() {
				this.audioFileList = [];
				this.pdfFileList = [];
				this.form = { test: [] };
				this.dialogVisible = false;
			},
		},
	};
</script>

<style lang="scss" scoped>
	.paper {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		.list {
			flex: 1;
		}
		.list,
		.page {
			margin-top: 20px;
		}
	}
</style>
